<?php
class LocumsController extends AppController {

	var $name = 'Locums';
	var $helpers = array('Html', 'Form');
	var $uses = array('Locum','Event', 'Vacancy','Apply','Rate','User','Store','Invite');
    var $components = array('Session','RequestHandler','Email','Image');
	
    
     public function beforeFilter() {
        parent::beforeFilter();
        // these action by pass authen
        $a_ActionAccess = array( 'register', 'save');
        // access these action if not login => redirect to login after back this action
        $a_ActionBack = array('view_apply', 'apply');
     	$user = $this->Session->read('User.User');
     	if ( !in_array($this->params['action'], $a_ActionAccess) )
     	{
     		if ( !$user )
     		{
     			if( in_array($this->params['action'], $a_ActionBack) )
     			{
     				$sz_BackLocumUrl = 'http://' . $_SERVER['HTTP_HOST'] . $this->here;
     				$this->Session->write('sz_BackLocumUrl', $sz_BackLocumUrl);
     			}
     			
     			$this->redirect(array('controller'=>'pages','action' => 'display'));
     		}
     		elseif( $user['UserType'] != 1 )
     		{
     			$this->redirect(array('controller'=>'errors','action' => 'permission'));
     		}
     	}
     	else 
     	{
     		if( $user )
     		{
     			$this->redirect(array('controller'=>'locums','action' => 'view/' . $user['id']));
     		}
     	}
     	
     	// Get i am invited
     	$a_Invite = $this->Invite->v_fGetInviteByLocumId( $user['id'] );
     	$this->set('a_LocumInvite', $a_Invite);
     	
    }
    
	function index() {
		$this->User->recursive = 0;
		$this->set('users', $this->paginate());
	}

	function view($id = null) {
		$sz_BackLocumUrl = $this->Session->read('sz_BackLocumUrl');
		if( $sz_BackLocumUrl )
		{
			$this->Session->delete('sz_BackLocumUrl');
			$this->redirect($sz_BackLocumUrl);
		}
        $this->layout='default';
		$this->set('title', 'Locum view profile');
		
		if ( $this->Session->read('User.User.id') != $id)
        {
        	$this->redirect(array('controller'=>'errors','action' => 'permission'));
        }
        $this->set('id',$id);
        
        $a_Events = $this->Event->a_fGetEvents($id); 
        $a_Event = explode(',',$a_Events['Event']['date']);
        $a_Temps = array();
        if(!empty($a_Event['0']))
        {
            foreach($a_Event as $event)
            {
                $a_Temps[] = strtotime($event);
            }
             sort($a_Temps);
	        $i_currentMonth = date('n');
	       // $a_EventMonth = explode('-',date('m'));
	        $i_eventMonth = date('m',$a_Temps[0]);
	        $jump = $i_eventMonth - $i_currentMonth;
	        $this->set('jump',$jump);
        }else {
        	$this->set('jump',0);
        }
       
        

		$a_VacanciesHot = $this->Vacancy->getListVacancyLastest();
        $this->set('a_VacanciesHot', $a_VacanciesHot);

		if (!$id) {
			$this->redirect(array('controller'=>'errors','action' => 'error404')); 
		}

        $locum =  $this->Locum->read(null, $id);
        $myApplied = $this->Apply->fGetListMyApplied($id);
        $this->set('myApplied',$myApplied);
        if(!empty($locum))
        {
        	if( $locum['Locum']['IsFirstLogin'] == 1 )
        		$this->redirect(array('controller'=>'locums','action' => 'edit/' . $id));
		    
        	// Calculate rate job
        	$a_RateJob = $this->Rate->a_fGetRateByLocumId( $id );
            
        	$i_NumberMaxRate = 0;
        	$i_RateAVG = 0;
        	$i_TotalRate = 0; 
        	foreach ( $a_RateJob as $RateJob )
        	{
                
        		$i_TotalRate += $RateJob['Rate']['rate'];

        		if( $RateJob['Rate']['rate'] == 5 )
        		{
        			$i_NumberMaxRate ++;
        		}
        	}
            
        	if( count($a_RateJob) > 0 )
        		$i_RateAVG = round( $i_TotalRate/count($a_RateJob) );	
        	
        	$locum['Locum']['i_NumberMaxRate'] = $i_NumberMaxRate;
        	$locum['Locum']['i_RateAVG'] = $i_RateAVG;
        		
        	$this->set('locum', $locum);
        }
        else
        {
           $this->redirect(array('controller'=>'errors','action' => 'error404')); 
        }
	}
    
    
    function getJson($id = null)
    {

         Configure::write('debug', 0);
         $this->autoRender = false;
         $this->layout =  false;
         $sz_StartEvent ='[';
         $sz_EndEvent =']';
         $user = $this->Session->read('User');
         if($user)
         {
           $a_Events = $this->Event->a_fGetEvents($id); 

           if($a_Events)
           {
               $a_Event = explode(',',$a_Events['Event']['date']);
               $i=1;
               $n= count($a_Event);
               foreach($a_Event as $k=>$event){
                  if($i < $n)
                    $sz_StartEvent .= '{"date": '.'"'.date('Y-m-d',strtotime($event)).'"'.'},';
                  else
                     $sz_StartEvent .= '{"date": '.'"'.date('Y-m-d',strtotime($event)).'"'.'}';
                  $i++;
               }
           }
           
         }
       
          
        echo $sz_StartEvent.$sz_EndEvent;
        $this->render(false);
    }
    
    
	function edit($id = null) {

        $this->set('title', 'Locum edit profile');
        $user = $this->Session->read('User');
        if ( $user['User']['id'] != $id)
        {
        	$this->redirect(array('controller'=>'errors','action' => 'permission'));
        }
        $a_Events = $this->Event->a_fGetEvents($user['User']['id']); 
        $this->set('id',$id);
        $this->set('a_Events',$a_Events);
        
        $a_Event = explode(',',$a_Events['Event']['date']);
        $a_Temps = array();
       
        if(!empty($a_Event['0']))
        {
            foreach($a_Event as $event)
            {
                $a_Temps[] = strtotime($event);
            }
            
            sort($a_Temps);
        	$i_currentMonth = date('n');
	       // $a_EventMonth = explode('-',date('m'));
	        $i_eventMonth = date('m',$a_Temps[0]);
	        $jump = $i_eventMonth - $i_currentMonth;
	       
	        $this->set('jump',$jump);
	 
        }else {
        	$this->set('jump',0);
        }

        $userInfo = $this->Session->read('User');
        $this->set('userInfo',$userInfo);
        
		if (!$id && empty($this->data)) {    
			$this->redirect(array('controller'=>'errors','action' => 'error404')); 
		}
		if (!empty($this->data)) {
              $this->Locum->set($this->data); 
              if($this->Locum->ValidateData() == true){ 
                    //build standard data
                     if($this->data['Locum']['ITCompatibility'])
                         $this->data['Locum']['ITCompatibility'] = implode(',',$this->data['Locum']['ITCompatibility']);
                         
                    if($this->data['Locum']['EssentialServices'])
                         $this->data['Locum']['EssentialServices'] = implode(',',$this->data['Locum']['EssentialServices']);
                    
                    if($this->data['Locum']['AdvancedServices'])
                         $this->data['Locum']['AdvancedServices'] = implode(',',$this->data['Locum']['AdvancedServices']);
                    
                    if($this->data['Locum']['EnhancedServices'])
                         $this->data['Locum']['EnhancedServices'] = implode(',',$this->data['Locum']['EnhancedServices']);
                    
                 //  $a_PostCode = $this->Locum->a_fGetPostCode($this->data['Locum']['Postcode']);
//                   if($a_PostCode)
//                   {
//                       $this->data['Locum']['latitude'] =$a_PostCode['Postcode']['latitude'];
//                       $this->data['Locum']['longitude'] =$a_PostCode['Postcode']['longitude']; 
//                   }
                   
                    
                    // Update the first login
                    $this->data['Locum']['IsFirstLogin'] = 0;
                    
                    $user['User']['IsFirstLogin'] =0;
                    $this->Session->write('User',$user );
                    // Update rate for profile
                    $sz_Rate = 0; // 5 - User Name; 5 - Email
                    
                    foreach ( $GLOBALS['FieldRate'] as $sz_Key )
                    {
                    	if( $this->data['Locum'][$sz_Key] != "" )
                    		$sz_Rate += 5;
                    }
                    $this->data['Locum']['Rate'] = $sz_Rate;
                    
                    if ($this->Locum->save($this->data)) {
                        //Save data to events table
                        $this->Event->v_fUpdateEvent($id,$this->data['Locum']['date']);
                        //$this->Session->setFlash(__('The Locums has been saved', true)); 
                        $this->redirect(array('controller'=>'locums','action' => 'view/'.$id));
                    } else {
                        $this->Session->setFlash(__('The Locums could not be saved. Please, try again.', true));
                    }
                }
		}
		if (empty($this->data)) {
			$this->data = $this->Locum->read(null, $id);   
		}
	}

    
    function upload_avatar()
    {   
        
        $user = $this->Session->read('User');
        $this->layout =false;
        if($this->data)
        {    
            if(empty($this->data['Locum']['mFile']))
            {
                //required variables are empty
                die ('Please choose a file to upload');
                return;
            }
            
            if($this->data['Locum']['mFile']['error'])
            {
                //File upload error encountered
                die($this->upload_errors($this->data['Locum']['mFile']['error']));
                return;
            }
            
            $FileName            = strtolower($this->data['Locum']['mFile']['name']); //uploaded file name
            $ImageExt            = substr($FileName, strrpos($FileName, '.')); //file extension
            $FileType            = $this->data['Locum']['mFile']['type']; //file type
            $FileSize            = $this->data['Locum']['mFile']["size"]; //file size
            $RandNumber           = rand(0, 9999999999); //Random number to make each filename unique.
            
            switch(strtolower($FileType))
            {
                //allowed file types
                case 'image/png': //png file
                case 'image/gif': //gif file 
                case 'image/jpeg': //jpeg file
                    break;
                default:
                    die('Unsupported File!');
                    return;
                    break; //output error
            }

           //File Title will be used as new File name
           $NewFileName = strtotime(date("Y-m-d H:i:s")).$FileName;
        
           //Rename and save uploded file to destination folder.
           if(move_uploaded_file($this->data['Locum']['mFile']["tmp_name"], WWW_ROOT.'img/avatar/'. $NewFileName ))
           {
           		// resize image
				$this->Image->load(WWW_ROOT.'img/avatar/'. $NewFileName);
		     	$this->Image->resizeToWidth(100);
		     	$this->Image->save(WWW_ROOT.'img/avatar/'. $NewFileName);
            	    
				$this->Locum->id    = $user['User']['id'];
				$this->Locum->saveField('Avatar',$NewFileName);

               // Insert info into database table.. do w.e!
               echo '<img src="'. Router::url('/').'app/webroot/img/avatar/'. $NewFileName.'" width="100" height="100" alt="Username">';
                
           }else{
                   die('Error uploading File!');
                   return;
           }
        }
         $this->render(false);
    }
    
     
	function register()
	{
         $this->layout =  false;
	}
    
    function save(){
        Configure::write('debug', 0);
        $a_Errors = array();
        $b_Error =true;
        $this->layout =  false;
        if(!empty($this->data))
        {  $this->Locum->set($this->data);
           if($this->data['Locum']['Username'] == '')
           {
               $a_Errors["Username"] = "Username is required";
               $b_Error =false;
           }else
           {
               
               if(preg_match("/^[a-z0-9]{4,10}$/i", $this->data['Locum']['Username']) > 0)
                {
                   if($this->Locum->checkUsernameExisted())
                   {
                       $b_Error = $b_Error && true;
                   }else
                   {
                         $a_Errors["Username"] = "Username exist";
                         $b_Error = $b_Error && false;
                   }
                   
                }
                else
                {
                    $a_Errors["Username"] = "Username must be integer and alphabet, between 4-10 characters";
                    $b_Error =$b_Error && false;
                }
           }
           
           if($this->data['Locum']['Password'] == '')
           {
               $a_Errors["Password"] = "Password is required";
               $b_Error =$b_Error && false;
           }
           
           if($this->data['Locum']['Email'] == '')
           {
               $a_Errors["Email"] = "Email is required";
               $b_Error =$b_Error && false;
           }else
           {
                if(preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^", $this->data['Locum']['Email']) > 0)
                {
                   if($this->Locum->checkEmailExisted())
                   {
                       $b_Error = $b_Error && true;
                   }else
                   {
                         $a_Errors["Email"] = "Email exist";
                         $b_Error = $b_Error && false;
                   }
                }
                else
                {
                    $a_Errors["Email"] = "Email is not validate";
                    $b_Error =$b_Error && false;
                }
           }
           
           if(!$b_Error)
           {    
                $a_Errors["success"]="faild";
                echo json_encode($a_Errors);
           }
           else
           {
               $sz_Password = $this->data['Locum']['Password'];
               $this->data['Locum']['Password'] = md5($this->data['Locum']['Password']); 
               $this->data['Locum']['UserType'] = 1;
               $this->data['Locum']['IsFirstLogin'] = 1;
               $this->data['Locum']['MatchMemberSince'] = date('Y/m/d');
               $this->data['Locum']['Rate'] = 10;
               if ($this->Locum->save($this->data)) {
               		
               		// Send mail login
               		$a_Email = array();
               		$a_Email["from"] = $GLOBALS['email_template_register']->from;
               		$a_Email["to"] = $this->data['Locum']['Email'];
               		$a_Email["subject"] = $GLOBALS['email_template_register']->subject;
               		$a_Email["content"] = str_replace(
               											array( '__USERNAME__', '__EMAIL__', '__PASSWORD__', '__LINKLOGIN__' ), 
               											array( $this->data['Locum']['Username'], $this->data['Locum']['Email'], $sz_Password, $_SERVER['HTTP_REFERER'] ), 
               											$GLOBALS['email_template_register']->content
               										);
               		$this->sendMail( $a_Email );
               		// End Send mail
               		
					$a_Errors["success"]="Thank you for your registration please check your inbox for confirmation.";
					echo json_encode($a_Errors["success"]);
                } 
                else 
                {
                    
                    $a_Errors["success"]="The Locums could not be saved. Please, try again";
                    echo json_encode($a_Errors);
                }
           }
           
          
        }
        else 
        {
        	exit('Data error');
        }
        $this->render(false);
    }
    
	function apply ( $i_VacancyId = null )
	{   
        $user = $this->Session->read('User');
        if(empty($user) || $user['User']['UserType'] != 1)
        {
         	$this->redirect(array('controller'=>'errors','action' => 'error404')); 
        }
        
        $b_Apply = $this->Apply->find('first',array('conditions'=>array('locum_id '=>$user['User']['id'],'vacancy_id'=>$i_VacancyId)));
        
        if(!empty($b_Apply))
            $this->set('b_Apply',true);
        else
            $this->set('b_Apply',false);
         
         //get email pharmacy
         $pharmacy_id = $this->Vacancy->find('first',array('fields'=>'Pharmacy_id','conditions'=>array('id'=>$i_VacancyId)));
         $pharmacy_email = $this->User->find('first',array('fields'=>'Email','conditions'=>array('id'=>$pharmacy_id['Vacancy']['Pharmacy_id'])));
		$a_Vacancy = $this->Vacancy->getVacancyById( $i_VacancyId );
        if(!empty($this->data))
        {
	        $a_Applies['Apply'] = $this->data['Locum'];
			$a_Applies['Apply']['locum_id'] = $user['User']['id'] ;
			$a_Applies['Apply']['vacancy_id'] = $this->data['Locum']['vacancy_id'];
			$a_Applies['Apply']['status'] = 1;
			$a_Vacancy = $this->Vacancy->getVacancyById( $this->data['Locum']['vacancy_id'] );
			
			$DateRange = explode(',',$a_Vacancy['Vacancy']['DateRange']);
			$DateRangeRemove = explode(',',$a_Applies['Apply']['event']);
			
			$DateRangeDiff = array_diff ($DateRange, $DateRangeRemove); 
			if($DateRangeDiff)
			{
			 $sz_DateRangeDiff =implode(',',$DateRangeDiff);
			   
			}else
			{
			  $sz_DateRangeDiff ='';
			}
			
		   if( $a_Applies['Apply']['HourlyRate'] =='')
		   		$a_Applies['Apply']['HourlyRate'] = $a_Vacancy['Vacancy']['HourlyRate'];
		   $a_Applies['Apply']['available'] =$sz_DateRangeDiff;
           
		   $this->Apply->create();
           if($this->Apply->save($a_Applies))
           {
           		$i_ApplyId =  $this->Apply->getInsertID();
           		// Delete this invite if have
           		$a_InviteLocum = $this->Invite->v_fGetInviteByLocumIdAndVacancyId($user['User']['id'], $i_VacancyId);
           		if( $a_InviteLocum )
           		{
           			$this->Invite->delete($a_InviteLocum['Invite']['id']);
           		}
			   	// Send email to locum
				$a_Email = array();
				$a_Email["from"] = $GLOBALS['email_template_register']->from;
				$a_Email["to"] = $user['User']['Email'];
				$a_Email["subject"] = "Applied vacancy successfully";
				$sz_LinkApplication = 'http://' . $_SERVER['HTTP_HOST'] . Router::url('/') . 'locums/view_apply/' . $i_ApplyId;
				$sz_Content = "Thank you for Applied vacancy. \n";
				$sz_Content .= "Please click <a href='" . $sz_LinkApplication ."'>here</a> to view details of this application";
				$a_Email["content"] = $sz_Content;
				$this->sendMail( $a_Email );
                
			   // Send email to pharmacy
			   	$a_Email = array();
				$a_Email["from"] = $GLOBALS['email_template_register']->from;
				$a_Email["to"] = $pharmacy_email['User']['Email'];
				$a_Email["subject"] = "Applied vacancy successfully";
				$sz_LinkActive = 'http://' . $_SERVER['HTTP_HOST'] . Router::url('/') . 'pharmacies/view_locum_profile/' .$user['User']['id'];               
				$sz_Content2 = "Please click <a href='" . $sz_LinkActive ."'>here</a> to view details of this locum";
				$a_Email["content"] = $sz_Content2;
				$this->sendMail( $a_Email );
			
                $this->redirect(array('controller'=>'locums','action' => 'apply_success'));
           }
        }
        
        $this->set('title', "Apply Vacancy");
        $a_Event = explode(',',$a_Vacancy['Vacancy']['DateRange']);
        $a_Temps = array();
        if(!empty($a_Event['0']))
        {
            foreach($a_Event as $event)
            {
                $a_Temps[] = strtotime($event);
            }
            sort($a_Temps);
	        $i_currentMonth = date('n');
	        $i_eventMonth = date('m',$a_Temps[0]);
	        $jump = $i_eventMonth - $i_currentMonth;
        	$this->set('jump',$jump);
        }else 
        	$this->set('jump',0);
       
        $this->set('Vacancy', $a_Vacancy);
	}
	
	function apply_success( $id = null )
	{
		$this->set('title', "application successfully sent");
        $this->set('search_url','searches/results'.$this->Session->read('search_url'));
	}
	
	function re_apply( $id = null )
	{
		Configure::write('debug', 0);
		$this->layout =  null;
		$this->layout =  false;
		$a_Errors["success"]="false";
		if( $id )
		{
			$LocupApplied = $this->Apply->fGetListLocumAppliedByApplyId($id);
			if( $LocupApplied )
			{
				$this->Apply->delete($id);
                $a_Errors["vacancy_id"] = $LocupApplied['Apply']['vacancy_id'];
				$a_Errors["success"]="true";
			}
		}
		echo json_encode($a_Errors);
		$this->render(false);
	}
    
    function view_apply($id =null)
    {
        $LocupApplied = $this->Apply->fGetListLocumAppliedByApplyId($id);
        if(!empty($LocupApplied) && $LocupApplied['Apply']['locum_id'] == $this->Session->read('User.User.id')){
            $a_Event = explode(',',$LocupApplied['Apply']['available']);
            $a_Temps = array();
            if(!empty($a_Event['0']))
            {
                foreach($a_Event as $event)
                {
                    $a_Temps[] = strtotime($event);
                }
                sort($a_Temps);
	            $i_currentMonth = date('n');
	           // $a_EventMonth = explode('-',date('m'));
	            $i_eventMonth = date('m',$a_Temps[0]);
	            $jump = $i_eventMonth - $i_currentMonth;
	           
	            $this->set('jump',$jump);
            }else 
            {
            	 $this->set('jump',0);
            }
            
             $this->set('LocupApplied', $LocupApplied);
        }
         else
        {
           $this->redirect(array('controller'=>'errors','action' => 'error404')); 
        }
    }
    
   function view_store($id = null) {
       
        $UserInfo = $this->Session->read('User');
        if(empty($UserInfo))
        {
            $this->redirect(array('controller'=>'pages','action' => 'display'));
        }
      
        if (!$id) {
            $this->Session->setFlash(__('Invalid User', true));
            $this->redirect(array('action' => 'index'));
        }
          
        $a_Stores =$this->Store->a_fGetStoresByStoreId($id);
        if(!empty($a_Stores)){
            $this->set('a_Stores', $a_Stores);
             }
        else
        {
            
            $this->redirect(array('controller'=>'errors','action' => 'error404'));
        }
    }
}
?>